/**
 * 维护敏感词拦截规则列表
 */
import type { OptionalFields } from '@gnlab/utils'
import { Service } from '@gnlab/utils'
import type { Services } from '@/services'
import { API } from '@/services/common/api'

export enum InterceptRuleType {
  Exact = 0, // 精确匹配
  Fuzzy = 1, // 模糊匹配
  Regex = 2, // 正则匹配
}

export interface InterceptRule {
  id: number
  name: string
  type: InterceptRuleType
  keyword: string
  enable: boolean
}

interface RespInterceptRule {
  Id: number
  RuleName: string
  RuleType: InterceptRuleType
  RuleContent: string
  Enable: boolean
}

function formatInterceptRule(raw: RespInterceptRule): InterceptRule {
  return {
    id: raw.Id,
    name: raw.RuleName,
    type: raw.RuleType,
    keyword: raw.RuleContent,
    enable: raw.Enable,
  }
}

export class SensitiveIntercepts extends Service<Services> {
  async load() {
    return API('/Config/GetSensitiveIntercepts', {
      formatter(raw: RespInterceptRule[]) {
        return raw.map(formatInterceptRule)
      },
    })
  }

  async addOrUpdate(rule: OptionalFields<InterceptRule, 'id'>) {
    return API('/Config/SaveSensitiveIntercept', {
      data: {
        Id: rule.id,
        RuleName: rule.name,
        RuleType: rule.type,
        RuleContent: rule.keyword,
        Enable: rule.enable,
      },
      formatter() {},
    })
  }

  async remove(id: number) {
    return API('/Config/RemoveSensitiveIntercept', {
      data: { Id: id },
      formatter() {},
    })
  }
}
